import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/config/address.dart';
import 'package:tiktokadult/config/config.dart';
import 'package:tiktokadult/hj_page/main_page/provider/msg_provider.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_utils.dart';
import 'package:tiktokadult/hj_page/pre_sale/pre_sale_provider.dart';
import 'package:tiktokadult/hj_utils/holiday_theme.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/global_store/store.dart';
import 'package:tiktokadult/tools_base/refresh/pull_refresh.dart';

import '../../tools_base/banner/ads_grid_view_widget.dart';
import 'home_mine_logic.dart';
import 'mine_setting/close_lock_dialog.dart';
import 'mine_setting/mine_password_page.dart';
import 'widgets/mine_info_widget.dart';
import 'widgets/vip_time_ac_view.dart';

//我的页面
class HomeMinePage extends StatefulWidget {
  const HomeMinePage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _HomeMinePageState();
  }
}

class _HomeMinePageState extends State<HomeMinePage> {
  late MineMainLogic logic;

  @override
  void initState() {
    logic = Get.put<MineMainLogic>(MineMainLogic());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MineMainLogic>(
      init: logic,
      builder: (controller) {
        return Consumer<GlobalStore>(builder: (_, store, ___) {
          return Scaffold(
            body: Stack(
              fit: StackFit.expand,
              children: [
                if (holidayTheme.openHoliday) ...[
                  Positioned(
                    top: 0,
                    left: 0,
                    right: 0,
                    child: Image.asset(HolidayTheme.theme.mineBg, fit: BoxFit.fitWidth),
                  ),
                ] else ...[
                  Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      child: Image.asset('mine_bg.webp'.mineImgPath))
                ],
                SafeArea(
                  child: pullYsRefresh(
                    onInit: (ctr) => controller.refreshCtr = ctr,
                    enablePullUp: false,
                    onRefresh: (refreshController) => controller.onRefresh(),
                    child: SingleChildScrollView(
                      child: Stack(
                        children: [
                          _buildTop(controller),
                          Column(
                            children: [
                              20.sizeBoxH,
                              MineInfoWidget(),
                              // 21.sizeBoxH,
                              // _buildCountView(),
                              21.sizeBoxH,
                              VipTimeAcView(),
                              12.sizeBoxH,
                              MineTaskMenuWidget(), //金币充值等
                              12.sizeBoxH,
                              MineFunctionGridView(), //我的购买/我的收藏/我的订阅/我的社区
                              12.sizeBoxH,
                              MineCooperationGridView(), //原创入驻/裸聊管理/原味商城/应用推荐
                              12.sizeBoxH,
                              MineServiceGridView(),//原创入驻/裸聊管理/原味商城/应用推荐
                              12.sizeBoxH,
                              _buildShop(),
                              AdsGridViewWidget(
                                8,
                                isBigStyle: true,
                                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                              ),
                              // Container(
                              //   margin: EdgeInsets.symmetric(horizontal: 16),
                              //   decoration: BoxDecoration(
                              //     borderRadius: BorderRadius.circular(9),
                              //     color: Colors.white.withOpacity(.05),
                              //   ),
                              //   child: Column(
                              //     crossAxisAlignment: CrossAxisAlignment.center,
                              //     children: [
                              //       ListView.builder(
                              //         physics: NeverScrollableScrollPhysics(),
                              //         shrinkWrap: true,
                              //         itemCount: controller.menuVerNameArr.length,
                              //         padding: EdgeInsets.zero,
                              //         itemBuilder: (context, index) {
                              //           String titleDesc = controller.menuVerNameArr[index];
                              //           String imagePath = 'mine_menu_${index + 1}.png'.mineImgPath;
                              //           return InkWell(
                              //             onTap: () => controller.menuVerTapEvent(index),
                              //             child: Column(
                              //               mainAxisSize: MainAxisSize.min,
                              //               children: [
                              //                 Container(
                              //                   height: 56,
                              //                   padding: EdgeInsets.symmetric(horizontal: 16),
                              //                   child: Row(
                              //                     children: [
                              //                       Image.asset(imagePath, width: 24, height: 24),
                              //                       12.sizeBoxW,
                              //                       Text(
                              //                         titleDesc,
                              //                         style: TextStyle(color: Colors.white.withOpacity(.9), fontSize: 14),
                              //                       ),
                              //                       const Spacer(),
                              //                       if (titleDesc == "填写邀请码" && controller.userInfo?.inviterCode?.isNotEmpty == true)
                              //                         Container(
                              //                           padding: EdgeInsets.only(right: 8),
                              //                           child: Text(
                              //                             controller.userInfo?.inviterCode ?? "",
                              //                             style: TextStyle(color: Color(0xff999999), fontSize: 14),
                              //                           ),
                              //                         ),
                              //                       Icon(
                              //                         Icons.arrow_forward_ios_rounded,
                              //                         size: 14,
                              //                         color: Colors.white,
                              //                       )
                              //                     ],
                              //                   ),
                              //                 ),
                              //                 0.5.line.paddingOnly(left: 16),
                              //               ],
                              //             ),
                              //           );
                              //         },
                              //       ),
                              //
                              //     ],
                              //   ),
                              // ),
                              Container(
                                margin: EdgeInsets.symmetric(horizontal: 16),
                                padding: EdgeInsets.symmetric(horizontal: 5,vertical: 8),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(9),
                                  color: Color(0xFF22242E),
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Padding(
                                        padding: EdgeInsets.only(left: 5, top: 10, right: 5),
                                        child: Row(
                                          children: [
                                            Text(
                                              '设置桌面图标',
                                              style: TextStyle(color: Color(0xffEFEFEF), fontSize: 14, fontWeight: FontWeight.w500),
                                            ),
                                            Spacer(),
                                            InkWell(
                                              onTap: () => controller.changeIcon(0),
                                              child: Text(
                                                '恢复默认',
                                                style: TextStyle(color: Color(0xff989898), fontSize: 12, fontWeight: FontWeight.w400),
                                              ),
                                            ),
                                          ],
                                        )),
                                    11.sizeBoxH,
                                    SizedBox(
                                      height: 76,
                                      child: ListView.separated(
                                        padding: EdgeInsets.symmetric(horizontal: 16),
                                        scrollDirection: Axis.horizontal,
                                        separatorBuilder: (_, __) => 7.sizeBoxW,
                                        itemCount: controller.iconList.length,
                                        itemBuilder: (BuildContext context, int index) {
                                          final data = controller.iconList[index];
                                          return InkWell(
                                            onTap: () => controller.changeIcon(index),
                                            child: Column(
                                              children: [
                                                Image.asset(
                                                  data.image,
                                                  width: 54,
                                                ),
                                                4.sizeBoxH,
                                                Text(
                                                  data.name,
                                                  style: TextStyle(
                                                    color: Colors.white.withOpacity(0.9),
                                                    fontSize: 12,
                                                  ),
                                                )
                                              ],
                                            ),
                                          );
                                        },
                                      ),
                                    ),
                                    10.sizeBoxH,
                                    Container(
                                      width: double.infinity,
                                      margin: EdgeInsets.symmetric(horizontal: 5,vertical: 3),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        crossAxisAlignment: CrossAxisAlignment.center,
                                        children: [
                                          Row(
                                            children: [
                                              Image.asset(
                                                'ic_lock.webp'.mineImgPath,
                                                width: 24,
                                                height: 24,
                                              ),
                                              Text(" 应用锁",style: TextStyle(color: Color(0xFFFFFFFF),fontSize: 12)),
                                            ],
                                          ),
                                          GestureDetector(
                                            onTap: () async{
                                              //锁屏密码
                                              if (globalStore.password.isNotEmpty) {
                                                final resp = await Get.dialog(CloseLockDailog());
                                                if (resp == true) {
                                                  Get.toNamed(MinePasswordPage.routeNmae, arguments: MinePasswordType.close);
                                                }
                                              } else {
                                                Get.toNamed(
                                                  MinePasswordPage.routeNmae,
                                                  arguments: MinePasswordType.setting,
                                                );
                                              }
                                            },
                                            child:  Image.asset(
                                              globalStore.password.isNotEmpty?'switch_on.webp'.mineImgPath:'switch_off.webp'.mineImgPath,
                                              width: 40,
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              // 20.sizeBoxH,
                              // Text(
                              //   '我的邀请码: ${store.meInfo?.promotionCode}',
                              //   style: textStyle(16, Color(0xffBDBDBD), FontWeight.w400),
                              // ),
                              // 6.sizeBoxH,
                              // Text(
                              //   '永久官方地址: ${Address.groundURl}',
                              //   style: textStyle(12, Color(0xff525252), FontWeight.w400),
                              // ),
                              30.sizeBoxH,
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                // Positioned(
                //   child: LuckyDrawButton(),
                //   right: 16,
                //   bottom: 160,
                // ),
                // Positioned(
                //   right: 16,
                //   bottom: 40,
                //   child: AIFloatingButton(),
                // ),
              ],
            ),
          );
        });
      },
    );
  }

  _buildTop(MineMainLogic _) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      child: Row(
        children: [
          Spacer(),
          // InkWell(
          //   onTap: () => MineUtils.goCSPage(),
          //   child: Image.asset(
          //     'mine_cs.png'.mineImgPath,
          //     width: 24,
          //   ),
          // ),
          Stack(
            children: [
              InkWell(
                onTap: () => _.menuTapEvent(3),
                child: Image.asset(
                  "ic_notice.webp".mineImgPath,
                  width: 24,
                ),
              ),
              Consumer<MineMsgProvider>(
                builder: (context, model, child) => Positioned(
                  right: 2,
                  top: 2,
                  child: model.buildTipsView(),
                ),
              ),
            ],
          ),
          12.sizeBoxW,
          InkWell(
            onTap: () => _.toSetting(context),
            child: Image.asset(
              "ic_setting.webp".mineImgPath,
              width: 24,
            ),
          ),
        ],
      ),
    );
  }

  //次数
  _buildCountView() {
    return Row(
      children: [
        50.sizeBoxW,
        Expanded(
          child: Consumer<GlobalStore>(
            builder: (context, store, child) => Consumer<PreSaleProvider>(
              builder: (context, provider, child) {
                int count = (store.wallet?.downloadCount ?? 0) + (provider.remain?.todayDownloadCount ?? 0);
                return _buildCountItem(count.toString(), '剩余缓存次数');
              },
            ),
          ),
        ),
        Container(
          color: Colors.white.withOpacity(.1),
          width: 0.5,
          height: 12,
        ),
        Expanded(
          child: Consumer<GlobalStore>(builder: (context, store, child) {
            final freeTimes = store.wallet?.aiUndressFreeTimes ?? 0;
            final presaleCount = presaleProvider.remain?.todayAiUndressCount ?? 0;
            //预售权益和免费次数的和
            final total = freeTimes + presaleCount;
            return _buildCountItem(total.toString(), '剩余AI脱衣次数');
          }),
        ),
        50.sizeBoxW,
      ],
    );
  }

  _buildCountItem(String count, String title) {
    return Column(
      children: [
        Text(
          count,
          style: textStyle(16, Colors.white, FontWeight.w500),
        ),
        4.sizeBoxH,
        Text(
          title,
          style: textStyle(12, Colors.white.withOpacity(.7), FontWeight.w400),
        ),
      ],
    );
  }

  Widget _buildShop() {
    if (Config.storeIsOpen == true) {
      return InkWell(
        onTap: () async => logic.toShop(),
        child: Padding(
          padding: const EdgeInsets.only(bottom: 10.0, left: 10, right: 10),
          child: AspectRatio(aspectRatio: 355 / 82, child: Image.asset('mine_shop_icon.webp'.mineImgPath)),
        ),
      );
    }
    return SizedBox.shrink();
  }

  @override
  void dispose() {
    Get.delete<MineMainLogic>();
    super.dispose();
  }
}
